package com.pearl.jacksonspringboot.demo.ser;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.util.Collection;
import java.util.List;

/**
 * 集成``
 * @author TD
 * @version 1.0
 * @date 2024/4/16
 */
public class NullValueBeanSerializerModifier extends BeanSerializerModifier {

    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
        for (BeanPropertyWriter propertyWriter : beanProperties) {
            Class<?> rawClass = propertyWriter.getType().getRawClass(); // 属性的真实类型
            if (rawClass.isArray() || Collection.class.isAssignableFrom(rawClass)){
                // 数组、集合类型时，注册 NullArrayJsonSerializer
                propertyWriter.assignNullSerializer(Jackson2NullValueSerializer.NullArrayJsonSerializer.instance);
            } else if ( CharSequence.class.isAssignableFrom(rawClass) || Character.class.isAssignableFrom(rawClass)) {
                // 字符类型时，注册 NullStringJsonSerializer
                propertyWriter.assignNullSerializer(Jackson2NullValueSerializer.NullStringJsonSerializer.instance);
            }
        }
        return beanProperties;
    }
}
